package cn.dxs.adt.http.news;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import cn.dxs.adt.http.ObjectLoader;
import cn.dxs.adt.http.RetrofitServiceManager;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Url;
import rx.Observable;
import rx.functions.Func1;

public class NewsLoader extends ObjectLoader {
    private static final String NEWS_URL = "https://54dxs.cn/crawler/newsBus/queryNewsListPaged";
    private NewsService mNewsService;

    public NewsLoader() {
        mNewsService = RetrofitServiceManager.getInstance().create(NewsService.class);
    }

    /**
     * 获取 来了，新闻早班车
     * @return
     */
    public Observable<List<NewsEntry>> getNewsList() {
        return observe(mNewsService.getNews(NEWS_URL)).map(new Func1<NewsResp, List<NewsEntry>>() {
            @Override
            public List<NewsEntry> call(NewsResp newsResp) {
                return newsResp.data;
            }
        });
    }

    public Observable<String> saveNews(String url) {
        JSONObject j = new JSONObject();
        try {
            j.put("url", url);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType json = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, j.toString());
        return observe(mNewsService.saveNews(body)).map(new Func1<NewsRespCommon, String>() {
            @Override
            public String call(NewsRespCommon newsRespCommon) {
                return null;
            }
        });
    }

    public interface NewsService {
        @GET
        Observable<NewsResp> getNews(@Url String url);

        @POST("newsBus/saveNews")
        Observable<NewsRespCommon> saveNews(@Body RequestBody requestBody);;
    }
}
